package com.shuqi.model.manager;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.text.TextUtils;

import com.shuqi.common.Constant;
import com.shuqi.common.LoginHelper;
import com.shuqi.common.MyTask;
import com.shuqi.common.Urls;
import com.shuqi.common.utils.BookContentUtils;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.Util;
import com.shuqi.database.dao.impl.BookCataLogDao;
import com.shuqi.database.dao.impl.BookInfoDao;
import com.shuqi.database.dao.impl.BookMarkInfoDao;
import com.shuqi.database.model.BookInfo;
import com.shuqi.database.model.BookMarkInfo;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.model.bean.BuyBookInfo;
import com.shuqi.model.bean.ChapterInfo;
import com.shuqi.model.net.HttpRequest;
import com.shuqi.model.net.UrlManager;
import com.shuqi.model.net.listener.HttpRequestListener;
import com.shuqi.model.parse.parser.BuyBookParser;
import com.shuqi.model.parse.parser.BuyChapterParser;

/**
 * 购买书籍管理
 * 
 * @author zhangpeng
 * 
 */
public class BuyBookManager {
    private static final String TAG = "BuyBookManager";

    /**
     * 购买章节回调
     * 
     * @author zhangpeng
     * 
     */
    public interface BuyChapterInfoInterface {
        public void onFinish(ChapterInfo info);
    }

    /**
     * 购买全本回调
     * 
     * @author zhangpeng
     * 
     */
    public interface BuyBookInfoInterface {
        public void onFinish(BuyBookInfo info);
    }

    /**
     * 购买全本
     * 
     * @param context
     * @param bookId
     * @param uid
     * @param itf
     */
    public static void buyBookOnline(final Context context, final String bookId,
            final String firstCid, final String uid, final BuyBookInfoInterface itf,
            final String price) {
        MyTask.runInBackground(new Runnable() {

            @Override
            public void run() {
                itf.onFinish(buyBookOnline(context, bookId, firstCid, uid, price));

            }
        }, true);
    }

    /**
     * 购买某章
     * 
     * @param context
     * @param bookId
     * @param cid
     * @param uid
     * @param itf
     */
    public static void buyChapterOnline(final Context context, final String bookId,
            final String cid, final String uid, final BuyChapterInfoInterface itf,
            final String price) {
        MyTask.runInBackground(new Runnable() {

            @Override
            public void run() {
                itf.onFinish(buyChapterOnline(context, bookId, cid, uid, price));

            }
        }, true);
    }

    /**
     * 购买某章
     * 
     * @param context
     * @param bookId
     * @param uid
     * @param cid
     * @return
     */
    public static ChapterInfo buyChapterOnline(Context context, final String bookId,
            final String cid, final String uid, final String price) {

        if (context == null || TextUtils.isEmpty(bookId) || TextUtils.isEmpty(uid)
                || Constant.GUEST_USER_ID.equals(uid)) {
            throw new IllegalArgumentException("bookId is null or uid is illegal");
        }
        final BuyChapterBean bean = new BuyChapterBean();
        HttpRequestListener httpRequsetListener = new HttpRequestListener() {

            @Override
            public List<BasicNameValuePair> setParams() {
                List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
                String timestamp = String.valueOf(System.currentTimeMillis());
                String strTimestamp = timestamp + uid;
                String md5_key = Util.getMD5(LoginHelper.Encrypt(strTimestamp));
                String key = "37e81a9d8f02596e1b895d07c171d5c9";
                String sign = Util.getMD5(uid + key + timestamp);
                params.add(new BasicNameValuePair("sign", sign));
                params.add(new BasicNameValuePair("PostTime", timestamp));// 时间戳
                params.add(new BasicNameValuePair("PostToken", md5_key));// md5
                return params;
            }

            @Override
            public String getRequestUrl() {
                // TODO Auto-generated method stub
                return Urls.getBuyBookUrl(uid, bookId, null, cid, true, price);
            }

            @Override
            public void action(int actionCode, Object object) {
                if (actionCode == EventTypeConstants.EVENT_SUCCESS) {
                    bean.info = (ChapterInfo) object;
                } else {// 否则通知失败
                    bean.info = new ChapterInfo();
                    bean.info.setMsg("联网失败");
                    bean.info.setCurChapterType(BookContentUtils.TYPE_DOWN_FAIL);
                    Log4an.d(TAG, "【buyChapterOnline】buyBookOnline err,code=" + actionCode);
                }
            }
        };
        HttpRequest request =
                new HttpRequest(context, UrlManager.COLUMN_DOMAIN_WRITE,
                        httpRequsetListener.getRequestUrl(), httpRequsetListener.setParams(),
                        httpRequsetListener);
        request.setDataParseAdapter(new BuyChapterParser());
        request.run();

        if (bean.info != null && "1".equals(bean.info.getCurChapterType())) {// 购买成功
            BookCataLogDao.getInstance().updateCatalogToPaid(bookId, "", uid, cid);
            Log4an.e(TAG, "buyChapterOnline------->" + bean.info);
        }
        return bean.info;
    }

    /**
     * 购买全本
     * 
     * @param context applicationcontext
     * @param bookId
     * @param uid
     * @param firstcid
     * @return
     */

    public static BuyBookInfo buyBookOnline(final Context context, final String bookId,
            final String firstCid, final String uid, final String price) {
        if (context == null || TextUtils.isEmpty(bookId) || TextUtils.isEmpty(uid)
                || Constant.GUEST_USER_ID.equals(uid)) {
            throw new IllegalArgumentException("bookId is null or uid is illegal");
        }
        final BuyBookBean bean = new BuyBookBean();
        HttpRequestListener httpRequsetListener = new HttpRequestListener() {
            @Override
            public List<BasicNameValuePair> setParams() {
                List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
                String timestamp = String.valueOf(System.currentTimeMillis());
                String strTimestamp = timestamp + uid;
                String key = "37e81a9d8f02596e1b895d07c171d5c9";

                String md5_key = Util.getMD5(LoginHelper.Encrypt(strTimestamp));
                String sign = Util.getMD5(uid + key + "full" + timestamp);
                Log4an.e("sign", ":" + sign + ";time:" + timestamp + ";uid:" + uid);
                params.add(new BasicNameValuePair("PostTime", timestamp));// 时间戳
                params.add(new BasicNameValuePair("PostToken", md5_key));// md5
                params.add(new BasicNameValuePair("sign", sign));
                return params;
            }

            @Override
            public String getRequestUrl() {
                return Urls.getBuyBookUrl(uid, bookId, "full", null, true, price);
            }

            @Override
            public void action(int actionCode, Object object) {
                if (actionCode == EventTypeConstants.EVENT_SUCCESS) {
                    bean.info = (BuyBookInfo) object;
                } else {// 否则通知失败
                    bean.info = new BuyBookInfo();
                    bean.info.setInfo("联网失败");
                    bean.info.setType("-1");
                    Log4an.d(TAG, "【buyBookOnline】buyBookOnline err,code=" + actionCode);
                }
            }
        };
        HttpRequest request =
                new HttpRequest(context, UrlManager.COLUMN_DOMAIN_WRITE,
                        httpRequsetListener.getRequestUrl(), httpRequsetListener.setParams(),
                        httpRequsetListener);
        request.setDataParseAdapter(new BuyBookParser());
        request.run();

        if (bean.info != null && "1".equals(bean.info.getType())) {// 购买成功
            BookMarkInfo oldMarkInfo = null;
            oldMarkInfo =
                    BookMarkInfoDao.getInstance().getBookMark(null, bookId, uid,
                            BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
            // Log4an.i(TAG, "oldMarkInfo is null=" + (oldMarkInfo == null ? true : false));
            // 更新书籍信息
            BookInfo bookInfo = new BookInfo();
            bookInfo.setBookId(bookId);
            bookInfo.setUserId(uid);
            bookInfo.setBookPayState(BookInfo.HAS_PAY);
            BookInfoDao.getInstance().saveOrUpdateBookInfo(bookInfo);
            bookInfo = BookInfoDao.getInstance().getBookInfo("", bookId, uid);
            // 更新章节信息,已购买
            BookCataLogDao.getInstance().updateCatalogAllToPaid(bookId, uid);
            String cid = null;
            String cName = "";
            int bookTotalByte = 0;
            int readByte = 0;
            float percent = 0;
            // 保留原始书签数据
            if (oldMarkInfo != null) {
                cid = oldMarkInfo.getChapterId();
                cName = oldMarkInfo.getChapterName();
                bookTotalByte = oldMarkInfo.getBookTotalByte();
                readByte = oldMarkInfo.getBookReadByte();
                percent = oldMarkInfo.getPercent();
            } else {
                cid = firstCid;
            }
            // Log4an.i(TAG, "cid=" + cid + ",cName=" + cName + ",bookTotalByte=" + bookTotalByte
            // + ",percent=" + percent);
            // 更新书签为未下载状态
            BookMarkInfo markInfo = new BookMarkInfo();
            markInfo.setBookId(bookId);
            markInfo.setUserId(uid);
            markInfo.setBookName(bookInfo.getBookName());
            markInfo.setBookType(BookMarkInfo.TYPE_NEW_PAY_BOOKMARK);
            markInfo.setBookReadByte(readByte);
            markInfo.setBookTotalByte(bookTotalByte);
            markInfo.setBookCoverImgUrl(bookInfo.getBookCoverImgUrl());
            markInfo.setChapterId(cid);
            markInfo.setChapterName(cName);
            markInfo.setPercent(percent);
            markInfo.setTotalChapter(bookInfo.getBookMaxOid());
            markInfo.setPayMode(String.valueOf(Constant.PAYMODE_BOOK));
            BookMarkInfoDao.getInstance().saveBookMark(markInfo);
        }

        return bean.info;
    }

    private static class BuyChapterBean {
        public ChapterInfo info;
    }

    private static class BuyBookBean {
        public BuyBookInfo info;
    }
}
